const shelljs = require('shelljs');
const path = require('path');
import { getWorkPath, getAppId, getTragetPath } from '../env'
import axios from 'axios';
// const FormData = require('form-data');
const fs = require('fs');
const AdmZip = require('adm-zip');

export function publist(publishPath) {
    console.log("publist:")
    /* const workPath=getWorkPath();
    //绝对路径
    const absolutePath=path.resolve(workPath,publishPath);
    const appid=getAppId();
    const distPath=getTragetPath();
    //删除文件夹
    shelljs.rm('-rf',absolutePath+'/'+appid);
    //创建文件夹
    shelljs.mkdir(absolutePath+'/'+appid);
    //复制文件夹
    shelljs.cp('-r',distPath+'/*',absolutePath+'/'+appid); */

    const appid = getAppId();
    // 要压缩的文件夹路径
    const folderPath = publishPath + '/dist/';
    // 生成的 ZIP 文件路径
    const zipFilePath = publishPath + '/dist/' + appid + '.zip';

    // 创建一个新的 AdmZip 实例
    const zip = new AdmZip();
    // 设置文件权限（例如，设置为 0o644，即读写权限）
    const filePermissions = 0o644;
    zip.addLocalFolder(folderPath, '', filePermissions); // 将文件夹添加到 ZIP 中

    // 写入 ZIP 文件
    zip.writeZip(zipFilePath);


    /* // 检查文件是否存在
    if (!shelljs.test('-e', zipFilePath)) {
        console.error(`文件不存在: ${zipFilePath}`);
        process.exit(1);
    }

    // 设置文件权限（例如，设置为 0o644，即读写权限）
    const permissions = '777';  // 也可以使用八进制表示法 0o644
    // 使用 chmod 命令设置权限
    const result = shelljs.chmod(permissions, zipFilePath);
    if (result.code === 0) {
        console.log(`文件权限已成功设置为 ${permissions}: ${zipFilePath}`);
    } else {
        console.error(`设置文件权限失败: ${result.stderr}`);
    } */

    fs.chmodSync(zipFilePath, 0o755);
    console.log('文件权限已同步更改。');

    // commitsource(publishPath + '/dist/' + appid + '.zip')
}

export function commitsource(path) {
    // 获取appid
    const appid = getAppId();
    let fileName=appid + '.zip';
    let filePath=path + '/dist/' + fileName;
    /* let fileName='app.js';
    let filePath=path + '/' + fileName; */
    return {
        fileName,
        filePath
    }
}
//上传提交小程序源码
export function commitsource__(path) {
    return new Promise((resolve, reject) => {
        let url = "http://local.mp.cn/app/commitsource";
        // 获取appid
        const appid = getAppId();
        // 创建一个 FormData 实例
        let formData = new FormData();
        console.log(path + '/' + appid + '.zip')
        // 读取文件并添加到 FormData
        formData.append('file', fs.createReadStream(path + '/dist/' + appid + '.zip'));
        formData.append('sssf', "my sssf");
        /* formData.append('sss', fs.createReadStream(path + "/123.jpg"), {
            filename: appid + '.zip',// 服务器接收到的文件名
            contentType: 'application/octet-stream'  // 文件的 MIME 类型
        }); */

        console.log("formData:",fs.createReadStream(path + "/123.jpg"))
        console.log("formData:",formData)

        // console.log(fs.createReadStream(path + '/dist/' + appid + '.zip'))

         // 配置axios请求
        const config = {
            headers: { 'Content-Type': 'multipart/form-data' },
            // headers: { 'Content-Type': 'application/octet-stream' },
            // headers: { ...formData.getHeaders() },
        };
        /*return axios({ url, method: 'POST', formData, config }).then(res => {
            console.log(res.data)
        }).catch(err => {

        }) */
    //    console.log(formData.getHeaders())
        axios.post(url, formDatas, config).then(res => {
            console.log(res.data);
        }).catch(err => {
            console.error(err);
        });

        /* fetch(url, { method: 'POST', body: formData })
        .then(function(res) {
            return res.json();
        }).then(function(json) {
            console.log(json);
        }); */

    });
}
